package com.fyzk.activity.user.xiangxi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.JCOrderInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.utils.DensityUtils;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.HandlerTypeUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.NoScrollListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

@ContentView(R.layout.jc_soccer_detail)
public class JCOrderDetailActivity extends BaseActivity {
    private Context context = this;
    private String id;
    @ViewInject(R.id.order_topview)
    private TopTitleView xiangxi_title_rl;
    @ViewInject(R.id.order_lotteryName)
    private TextView tv_caiZhong;
    @ViewInject(R.id.xiangxi_fanganmoney)
    private TextView tv_money;
    @ViewInject(R.id.xiangxi_beishu)
    private TextView tv_beiShu;
    @ViewInject(R.id.xiangxi_fanganid)
    private TextView tv_id;
    @ViewInject(R.id.xiangxi_time)
    private TextView tv_time;
    @ViewInject(R.id.xiangxi_state)
    private TextView tv_state;
    @ViewInject(R.id.xiangxi_zjmoney)
    private TextView tv_prizeMoney;
    @ViewInject(R.id.xiangxi_content)
    protected LinearLayout ll_content;
    @ViewInject(R.id.ll_plan_detail)
    protected LinearLayout ll_detail;
    @ViewInject(R.id.order_txt_continue)
    private TextView tv_jiXu;
    @ViewInject(R.id.xiangxi_bettype)
    private TextView xiangxi_bettype;
    @ViewInject(R.id.xiangxi_tiket)
    private TextView xiangxi_tiket;
    @ViewInject(R.id.tv_zhushu)
    private TextView zhushu;
    @ViewInject(R.id.tv_youhua)
    private TextView youhua;
    @ViewInject(R.id.iv_plan_detail)
    private RelativeLayout ivDetail;
    @ViewInject(R.id.iv_plan_content)
    private RelativeLayout ivContent;
    @ViewInject(R.id.iv_icon)
    private ImageView ivIcon;
    @ViewInject(R.id.myrr_item_type)
    private TextView type_secret;

    @ViewInject(R.id.ll2)
    private LinearLayout ll2;
    @ViewInject(R.id.viewLine3)
    private View viewLine3;
    @ViewInject(R.id.rl_optimize)
    private RelativeLayout rl_optimize;
    @ViewInject(R.id.ll_optimize_details)
    private LinearLayout ll_optimize_details;

    private double leftMoney;   // 用户彩金
    private int orderMoney;     // 订单彩金(整数，用int)
    private long lowMoney;       // 待支付差额(支付必须是整数)
    private boolean detailIsShow = true;
    private boolean contentIsShow = true;
    private boolean optimizeIsShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        info();
        id = getIntent().getStringExtra(IntentParamUtils.BETDETAILID);
        DJ_ProgressDialog.show(getContext(), true, true);
        getOrderInfo();
        requestLeftMoney();
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }

    private void getOrderInfo() {
        JSONObject json = new JSONObject();
        try {
            json.put("orderid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.COMMON_BET_RECORD_DETAIL, Commands.ORDERINFO, json, true);
    }

    JCOrderInfo info;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.COMMON_BET_RECORD_DETAIL:
                perseOrder(resultBean);
                setViewValue();
                break;
            case CommandUtil.ACCOUNT_MONEY:
                AccountMoneyResponse accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);
                leftMoney = Double.parseDouble(PublicMethod.formatBalance(accountMoneyResponse.getBalance()));
                break;
        }
    }

    protected void parserMessage(Message msg) {
        DJ_ProgressDialog.dissmiss();
        switch (msg.what) {
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_RECORDDETAIL_SUCCESS:
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_FAIL:
                Toast.makeText(this, "联网失败", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }

    private void info() {
        xiangxi_title_rl.setOnTitleClickListener(this);
        tv_jiXu.setOnClickListener(this);

    }

    public void setViewValue() {
        if (info.getLotteryType() == 3001 || info.getLotteryType() == 3002 || info.getLotteryType() == 3003 || info.getLotteryType() == 3004
                || info.getLotteryType() == 3005) {
            ivIcon.setImageResource(R.drawable.basket_detail_icon);
        } else {
            ivIcon.setImageResource(R.drawable.soccer_detial_icon);
        }
        if (info.getOptimizeDetail() == null || info.getOptimizeDetail().size() == 0) {
            youhua.setVisibility(View.GONE);
            ll2.setVisibility(View.GONE);
            viewLine3.setVisibility(View.GONE);
        } else {
            youhua.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.VISIBLE);
            viewLine3.setVisibility(View.VISIBLE);
            initOptimizeView();
        }
        if (!TextUtil.isEmpty(info.getIsRecharge()) && info.getIsRecharge().equals("1")) {
            xiangxi_title_rl.setRightVisible(View.VISIBLE);
            xiangxi_title_rl.setRightTxt("支付");
        } else {
            xiangxi_title_rl.setRightVisible(View.INVISIBLE);
        }
        tv_caiZhong.setText(info.getLotteryTypeName());
        tv_money.setText("付款彩金：" + PublicMethod.formatMoney(info.getAmount()) + "米");
        orderMoney = info.getAmount() / 100;

        tv_beiShu.setText("倍数" + info.getMultiple() + "倍");
        tv_id.setText("" + id);
        xiangxi_bettype.setText("" + info.getBettype());
        tv_time.setText("" + info.getReceiveTime());
        tv_state.setText("" + info.getOrderResultStatusName());
        zhushu.setText(info.getBetnum() + "注");

        if (info.getAddprize() > 0) {
            tv_prizeMoney.setText(Html.fromHtml(String.valueOf(
                    PublicMethod.formatMoney(info.getPrize() * 1.0)) + "<font color='#666666'>(加奖</font>"
                    + PublicMethod.formatMoney(info.getAddprize() * 1.0) + "<font color='#666666'>)</font>米"));
        } else {
            tv_prizeMoney.setText(PublicMethod.formatMoney(info.getPrize() * 1.0) + "米");
        }

        xiangxi_tiket.setText(info.getOrderStatusName());
        if (info.getWay() != 0) {//保密
            ll_content.setVisibility(View.GONE);
            type_secret.setVisibility(View.VISIBLE);
        } else {
            type_secret.setVisibility(View.GONE);
            View view = View.inflate(this, R.layout.layout_jcbetcode, null);
            TextView playName = (TextView) view.findViewById(R.id.playName);
            playName.setText("玩法:" + info.getDetail().getPlayName());
            ListView ls = (ListView) view.findViewById(R.id.jc_betcode);
            List<JCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens = info.getDetail()
                    .getRaceBetcode();
            BetCodeAdapter betCodeAdapter = new BetCodeAdapter(raceBetcodeBeens);
            ls.setAdapter(betCodeAdapter);
            ll_content.removeAllViews();
            ll_content.addView(view);
        }


        ivContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (contentIsShow) {
                    contentIsShow = false;
                    ll_content.setVisibility(View.GONE);
                    type_secret.setVisibility(View.GONE);
                } else {
                    contentIsShow = true;
                    if (info.getWay() != 0) {
                        type_secret.setVisibility(View.VISIBLE);
                    } else {
                        ll_content.setVisibility(View.VISIBLE);
                    }

                }
            }
        });

        rl_optimize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (optimizeIsShow) {
                    optimizeIsShow = false;
                    ll_optimize_details.setVisibility(View.GONE);
                } else {
                    optimizeIsShow = true;
                    ll_optimize_details.setVisibility(View.VISIBLE);
                }
            }
        });

        ivDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (detailIsShow) {
                    detailIsShow = false;
                    ll_detail.setVisibility(View.GONE);
                } else {
                    detailIsShow = true;
                    ll_detail.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 加载奖金优化详情
     */
    private void initOptimizeView() {
        ll_optimize_details.removeAllViews();
        List<JCOrderInfo.OptimizeDetailBean> optimizeDetailBeans = info.getOptimizeDetail();
        for (JCOrderInfo.OptimizeDetailBean bean : optimizeDetailBeans) {
            List<JCOrderInfo.OptimizeDetailBean.RacedetailsBean> racedetailsBeans = bean.getRacedetails();
            LinearLayout childLl = new LinearLayout(context);
            childLl.setOrientation(LinearLayout.VERTICAL);
            for (JCOrderInfo.OptimizeDetailBean.RacedetailsBean childBean : racedetailsBeans) {
                LinearLayout grandsonLl = new LinearLayout(context);
                grandsonLl.setOrientation(LinearLayout.HORIZONTAL);
                TextView tvHomeAndAway = new TextView(context);
                LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(context, 30));
                tvHomeAndAway.setLayoutParams(params1);
                tvHomeAndAway.setGravity(Gravity.CENTER_VERTICAL);
                tvHomeAndAway.setText(childBean.getHomeTeam() + "（主） vs （客）" + childBean.getAwayTeam());
                tvHomeAndAway.setTextColor(context.getResources().getColorStateList(R.color.color_333333));

                TextView tvBetCode = new TextView(context);
                LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(context, 30));
                params2.setMargins(30, 0, 0, 0);
                tvBetCode.setLayoutParams(params2);
                tvBetCode.setGravity(Gravity.CENTER_VERTICAL);
                tvBetCode.setText(childBean.getBetcode());
                tvBetCode.setTextColor(context.getResources().getColorStateList(R.color.top_bg));

                grandsonLl.addView(tvHomeAndAway);
                grandsonLl.addView(tvBetCode);
                childLl.addView(grandsonLl);
            }
            TextView tvNum = new TextView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(context, 30));
            tvNum.setLayoutParams(params);
            tvNum.setText(racedetailsBeans.size() + "串1 " + bean.getBetNum() + "注");
            tvNum.setTextColor(context.getResources().getColorStateList(R.color.color_333333));

            View lineView = new View(context);
            LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
            lineView.setLayoutParams(lineParams);
            lineView.setBackgroundResource(R.color.color_bfbfbf);

            childLl.addView(tvNum);
            childLl.addView(lineView);
            ll_optimize_details.addView(childLl);
        }
    }


    class BetCodeAdapter extends BaseAdapter {

        private List<JCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens;

        BetCodeAdapter(List<JCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens) {
            this.raceBetcodeBeens = raceBetcodeBeens;
        }

        @Override
        public int getCount() {
            return raceBetcodeBeens.size();
        }

        @Override
        public JCOrderInfo.DetailBean.RaceBetcodeBean getItem(int position) {
            return raceBetcodeBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(JCOrderDetailActivity.this, R.layout
                        .layout_jcbetcode_item, null);
                holder = new ViewHolder();
                holder.teamname = (TextView) convertView.findViewById(R.id.team_homeaway);
                holder.score = (TextView) convertView.findViewById(R.id.team_score);
                holder.result = (NoScrollListView) convertView.findViewById(R.id.list_contentsbean);
                holder.id = (TextView) convertView.findViewById(R.id.team_id);
                holder.isDan = (TextView) convertView.findViewById(R.id.team_isDan);
                holder.line = (View) convertView.findViewById(R.id.line);
                holder.line2 = (View) convertView.findViewById(R.id.line2);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            JCOrderInfo.DetailBean.RaceBetcodeBean raceBetcodeBean = raceBetcodeBeens.get(position);

            if (raceBetcodeBean.getDan() == 1) {
                holder.isDan.setVisibility(View.VISIBLE);
            } else {
                holder.isDan.setVisibility(View.INVISIBLE);
            }
            String weedDay = raceBetcodeBean.getOfficialWeekDay();
            String id = "";
            if (!TextUtil.isEmpty(weedDay)) {   // 北单没有返回星期
                id = raceBetcodeBean.getOfficialWeekDay() + "\n" + raceBetcodeBean.getMatchNum();
            } else {
                id = raceBetcodeBean.getMatchNum();
            }
            holder.id.setText(id);
            String team;
            if (info.getLotteryType() == LotteryIDUtils.JLDXF_LOTTERY_ID_INT || info
                    .getLotteryType() == LotteryIDUtils.JLHH_LOTTERY_ID_INT || info
                    .getLotteryType() == LotteryIDUtils.JLSF_LOTTERY_ID_INT || info
                    .getLotteryType() == LotteryIDUtils.JLRSF_LOTTERY_ID_INT || info
                    .getLotteryType() == LotteryIDUtils.JLSFC_LOTTERY_ID_INT) {
                team = raceBetcodeBean
                        .getAwayTeam() + "(客)\nVS\n" + raceBetcodeBean.getHomeTeam() + "(主)";
            } else {
                team = raceBetcodeBean.getHomeTeam() + "(主)\n" + raceBetcodeBean.getHandicap() + "\n" + raceBetcodeBean
                        .getAwayTeam() + "(客)";
            }

            holder.teamname.setText(team);
            String homeScore = "-";
            String awawScore = "-";
            if (!TextUtil.isEmpty(raceBetcodeBean.getHomeScore())) {
                homeScore = raceBetcodeBean.getHomeScore();
            }
            if (!TextUtil.isEmpty(raceBetcodeBean.getAwayScore())) {
                awawScore = raceBetcodeBean.getAwayScore();
            }
            StringBuilder resultBulidler = new StringBuilder();
            if (!raceBetcodeBean.getContents().isEmpty()) {
                for (JCOrderInfo.DetailBean.RaceBetcodeBean.ContentsBean contentsBean : raceBetcodeBean.getContents()) {
                    resultBulidler.append(contentsBean.getResult() + "\n");
                }
            }
            if(raceBetcodeBean.getHomeTeam().equals("绿色森林")){
                Log.e("fjl",resultBulidler.toString().trim());
            }
            if(TextUtils.isEmpty(resultBulidler.toString().trim())||TextUtils.equals("null",resultBulidler.toString().trim())){
                holder.score.setText("");
            }else {
                holder.score.setText(homeScore + ":" + awawScore + "\n" + resultBulidler.toString().trim());
            }

            CodeContentAdapter codeContentAdapter = new CodeContentAdapter(raceBetcodeBean
                    .getContents());
            holder.result.setAdapter(codeContentAdapter);

            if (position >= raceBetcodeBeens.size() - 1) {
                holder.line.setVisibility(View.GONE);
                holder.line2.setVisibility(View.VISIBLE);
            } else {
                holder.line2.setVisibility(View.GONE);
                holder.line.setVisibility(View.VISIBLE);
            }

            return convertView;
        }


        class ViewHolder {
            TextView isDan;
            TextView id;
            NoScrollListView result;
            TextView teamname;
            TextView score;
            View line;
            View line2;
        }
    }

    class CodeContentAdapter extends BaseAdapter {

        private List<JCOrderInfo.DetailBean.RaceBetcodeBean.ContentsBean> raceBetcodeBeens;

        CodeContentAdapter(List<JCOrderInfo.DetailBean.RaceBetcodeBean.ContentsBean>
                                   raceBetcodeBeens) {
            this.raceBetcodeBeens = raceBetcodeBeens;
        }

        @Override
        public int getCount() {
            return raceBetcodeBeens.size();
        }

        @Override
        public JCOrderInfo.DetailBean.RaceBetcodeBean.ContentsBean getItem(int position) {
            return raceBetcodeBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(JCOrderDetailActivity.this, R.layout
                        .layout_jcbetcode_contentbean_item, null);
                holder = new ViewHolder();
                holder.payType = (TextView) convertView.findViewById(R.id.team_paytype);
                holder.result = (TextView) convertView.findViewById(R.id.team_result);
                holder.betcode = (TextView) convertView.findViewById(R.id.team_betcontent);
                holder.line = (View) convertView.findViewById(R.id.team_result_line);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            JCOrderInfo.DetailBean.RaceBetcodeBean.ContentsBean raceBetcodeBean =
                    raceBetcodeBeens.get(position);

            String payTypeStr = raceBetcodeBean.getLotteryTypeName();
            if (TextUtil.isEmpty(payTypeStr)) {     // 北单特殊
                payTypeStr = info.getLotteryTypeName();
            }
            holder.payType.setText(payTypeStr);
            String resultStr = raceBetcodeBean.getResult();
            if (TextUtil.isEmpty(resultStr)) {
                resultStr = "--";
            }
            holder.result.setText(Html.fromHtml(resultStr));
            holder.betcode.setText(Html.fromHtml(raceBetcodeBean.getBetcode().replace(",", "<br><br>")));

            if (position == raceBetcodeBeens.size() - 1) {
                holder.line.setVisibility(View.GONE);
            } else {
                holder.line.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        class ViewHolder {
            TextView payType;
            TextView result;
            TextView betcode;
            View line;

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.order_txt_continue:
                if (AppLotteryCodeListManager.betType == AppLotteryCodeListManager.OKTOBACK) {
                    finish();
                    return;
                }
                try {
                    if (ContinueBuy.jiXu(getContext(), info.getLotteryType())) {
                        finish();
                    }
                } catch (Exception e) {

                }
                break;
            default:
                break;
        }
    }

    protected void perseOrder(StringResultBean resultBean) {
        info = JSON.parseObject(resultBean.getData(), JCOrderInfo.class);
    }

    @Override
    public void onRightClick() {
        lowMoney = orderMoney - (int) leftMoney;
        Intent intent = new Intent(getContext(), RechargeActivity.class);
        intent.putExtra(IntentParamUtils.ORDER_ID, id);
        intent.putExtra(IntentParamUtils.lowMoney, lowMoney);
        startActivityForResult(intent, IntentParamUtils.LOWMONEY_TO_RECHARGE_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentParamUtils.LOWMONEY_TO_RECHARGE_OK) {  // 支付完返回 刷新订单
            getOrderInfo();
        }
    }
}
